<?php
class database_mysql
{
    var $servername =null;
	var $databasename =null;
    var $username =null;
    var $password =null;
	var $connect = null;
	var $row_count = null;
	var $MYSQL_TYPES_NUMERIC= 'int real double tinyint';
	var $MYSQL_TYPES_DATE = 'datetime timestamp year date time';
	var $MYSQL_TYPES_STRING = 'string blob text enum varchar';
	var $auto_slashes;
	
	function __construct()
    {		global $arrconnect;						
			$this->servername = $arrconnect["host"];
			$this->databasename = $arrconnect["db"];
			$this->username = $arrconnect["user"];
			$this->password = $arrconnect["pass"];
	}
	
	public function mysql_get_connection()
    {
   		$connect = mysql_connect($this->servername, $this->username, $this->password);
   	 	if (!$connect) {
			$this->writeDiary($this->servername."__".$this->username."__".$this->password."\r\n =>".mysql_error(), PATH_LIB."diaryLog/error.php");
			die('Could not connect MySQL: ' . mysql_error());
    	}
    	return $connect;
    }
	
	public function mysql_check_string($strDirty)
	{	
		$this->connect=$this->mysql_get_connection();
		mysql_select_db ($this->databasename, $this->connect);
		mysql_query("SET NAMES 'utf8'");
		
		if (get_magic_quotes_gpc())
		{
			$clean = stripslashes($strDirty);	 
		}
		else{
			$clean = mysql_real_escape_string($strDirty);
		}
		return trim($clean);
	}
	    
    public function mysql_tbl_list()
    { 
		$this->connect=$this->mysql_get_connection();
        $result = @mysql_list_tables($this->databasename, $this->connect);
        $num = mysql_num_rows($result);
        $i = 0;
        while($i<$num){
            $arr [] = @mysql_db_name($result,$i);
            $i++;
        }
		if(!$result){
			$this->writeDiary($select."\r\n".mysql_error(), PATH_LIB."diaryLog/error.php");
			die(mysql_error());
		}
 		return $arr;
    }
    public function mysql_selected($select)
    { 
        /* $select.'<br><br><br>'; */
		
        $select = str_replace(array("\n","\r","\t"),' ',$select);
		$this->connect=$this->mysql_get_connection();
		mysql_select_db ($this->databasename, $this->connect);
		mysql_query("SET NAMES 'utf8'");
		$result = mysql_query($select, $this->connect);
		$this->row_count = mysql_num_rows($result);
		if(!$result){
			$this->writeDiary($select."\r\n".mysql_error(), PATH_LIB."diaryLog/error.php");
			die(mysql_error());
		}
 		return $result;
    }
	
	public function mysql_get_row_count()
	{
		return $this->row_count;
	}
	
	public function mysql_select_one($sql) 
	{
		$this->_last_query = $sql;
		$r = $this->mysql_selected($sql);
		$ret = mysql_result($r, 0);
		return $ret;
	}
	
	public function mysql_one_row($select)
	{
		$row = array();
		$result = $this->mysql_selected($select);
		if($this->mysql_get_row_count() == 1){
			$row = mysql_fetch_assoc($result);
		}
		return $row;
	}
	
	public function mysql_fetch_all_rows($select)
	{
       
		$arr = array();
		$result = $this->mysql_selected($select);
		if($this->mysql_get_row_count()){
			while($row = mysql_fetch_assoc($result))
			{
				array_push($arr,$row);
			}
		}
		return $arr;
	}
    
    public function mysql_fetch_one_rows($select)
	{
		$result = $this->mysql_selected($select);
		if($this->mysql_get_row_count()){
			$row = mysql_fetch_assoc($result);
            return $row;
		}
	}
    
	
	public function mysql_update_insert($query)
    {
        $query = str_replace(array("\n","\r","\t"),' ',$query);
		$this->connect=$this->mysql_get_connection();
		mysql_select_db ($this->databasename, $this->connect);
		mysql_query("SET NAMES 'utf8'");
		$result = mysql_query($query, $this->connect);
 		if(!$result){
			$this->writeDiary($query."\r\n =>".mysql_error(), PATH_LIB."diaryLog/error.php");
			die(mysql_error());
		}else{
			$this->writeDiary($query, PATH_LIB."diaryLog/addData.php");
		}
		return $result;
    }
	
	public function mysql_delete($query)
    {
        $query = str_replace(array("\n","\r","\t"),' ',$query);
		$this->connect=$this->mysql_get_connection();
		mysql_select_db ($this->databasename, $this->connect);
		mysql_query("SET NAMES 'utf8'");
		$result = mysql_query($query, $this->connect);
 		if(!$result){
			$this->writeDiary($query."\r\n =>".mysql_error()."\r\n\r\n", PATH_LIB."diaryLog/error.php");
			die(mysql_error());
		}else{
			$this->writeDiary($query, PATH_LIB."diaryLog/DelData.php");
		}
		return $result;
    }
	
	public function writeDiary($message, $file) 
	{		
		$handle = fopen($file, 'a+'); 
		fwrite($handle, "\r\n".date('Y-m-d G:i:s') . " - " . $message . "\r\n");
		fclose($handle); 
	}
	
	public function mysql_close_connection()
	{
		mysql_close($this->connect); 
	}

    /*
    Khong can sai ham mysql_check_string
    **/
 	public function mysql_insert_array($table, $data)
	{
		if (empty($data)) {
			$this->last_error = "Array empty!";
			return false;
		}
		
		$cols = '(';
		$values = '(';
		$table = $this->mysql_check_string($table);
		foreach ($data as $key=>$value)
		{
			$value = $this->mysql_check_string($value);
            $key = $this->mysql_check_string($key);
            
            $cols .= "`$key`,";  
			$col_type = $this->mysql_get_column_type($table, $key);
			
			if (substr_count($this->MYSQL_TYPES_NUMERIC, "$col_type "))
			{
				$values .= "'$value',";
			}
			elseif (substr_count($this->MYSQL_TYPES_DATE, "$col_type "))
			{
				$value = $this->sql_date_format($value, $col_type);
				$values .= "'$value',";
			}
			elseif (substr_count($this->MYSQL_TYPES_STRING, "$col_type "))
			{
				if ($this->auto_slashes)
					$value = addslashes($value);
				$values .= "'$value',";  
			}else {
				$values .= "NULL,";   
			}
 
		}
		$cols = rtrim($cols, ',').')';
		$values = rtrim($values, ',').')';     
		$res = $this->mysql_update_insert("INSERT INTO $table $cols VALUES $values");
		return $res;
	}
   
    /*
    Khong can sai ham mysql_check_string
    **/
	public function mysql_update_array($table, $data, $condition)
	{
		if (empty($data)) {
			$this->last_error = "You must pass an array to the mysql_update_array() function.";
			return false;
		}
		$sql = "UPDATE `$table` SET";
        $table = $this->mysql_check_string($table);
		foreach ($data as $key=>$value)
		{
            $value = $this->mysql_check_string($value);
            $key = $this->mysql_check_string($key);
            
			$sql .= " `$key`=";  
			$col_type = $this->mysql_get_column_type($table, $key);
			
			if (substr_count($this->MYSQL_TYPES_NUMERIC, "$col_type "))
			{
				$sql .= "'$value',";
			}
			elseif (substr_count($this->MYSQL_TYPES_DATE, "$col_type "))
			{
				$value = $this->sql_date_format($value, $col_type);
				$sql .= "'$value',";
			}
			elseif (substr_count($this->MYSQL_TYPES_STRING, "$col_type "))
			{
				if ($this->auto_slashes) $value = addslashes($value);
				$sql .= "'$value',";  
			}else{
				$sql .= "NULL,";   
			} 
			
		}
		$sql = rtrim($sql, ',');
		if (!empty($condition))
			$sql .= " WHERE $condition";
		return $this->mysql_update_insert($sql);
	}
	
	public function mysql_check_exists($table_name, $col_name, $value, $condition = NULL)
	{
		$sql = "select `$col_name` from `$table_name` where `$col_name`='$value'";
		if($condition!=NULL)
		{
			$sql .= " and $condition";
		}
		$r = $this->mysql_selected($sql);
		if($r)
		{
			return $this->row_count > 0;
		}
	}
	   
    public function mysql_get_column_type($table, $column)
	{
      $this->connect=$this->mysql_get_connection();
      $r = mysql_query("SELECT `$column` FROM `$table`",$this->connect);
      if (!$r) {
          $this->writeDiary(mysql_error()."\r\n\r\n", PATH_LIB."diaryLog/error.php");
          return false;
      }
      $ret = mysql_field_type($r, 0);
      if (!$ret) {
         $this->db_error_log("Unable to get column information on $table.$column.");
         mysql_free_result($r);
         return false;
      }
      mysql_free_result($r);
      return $ret;
      
    }
   
}
 
?>